const express = require('express');
const router = express.Router();
let db = require('../../db/mysql')
const response = require('../../response')
const request = require('../../request')
const md5 = require('md5')
const Base64 = require('js-base64').Base64
const unit = require('../../unit')
// 引入实体
db = new db()
/**
 * @apiDefine UserNotFoundError
 * @apiErrorExample {json} Error-Response:
 * {
 *      "code" : 312,
 *      "data" : "请先登录"
 * }
 */

/**
 * @apiDefine Error
 * @apiErrorExample {json} Error-Response:
 * {
 *      "code" : 500,
 *      "data" : "错误信息"
 * }
 */

/**
 * @api {post} /user/login 用户登录
 * @apiDescription 用户登录
 * @apiName user-login
 * @apiGroup User
 * @apiParam {string} username 用户名 *
 * @apiParam {string} password 密码(MD5加密) *
 * @apiSuccessExample {json} Success-Response:
 *  {
 *      "code" : 200,
 *      "data" : "登录成功"
 *  }
 * @apiSampleRequest /user/login
 * @apiUse Error
 * @apiVersion 1.0.0
 */
router.post('/login', function(req, res, next) {
  let check = request.checkParams(req.body, 'userLoginInput')
  if (check.error) {
    response.errorList(res, check.data)
    return false
  }
  let data = {...check.data}
  let where = [
    {
      name: 'username',
      value: data.username
    },
    {
      name: 'password',
      value: Base64.encode(data.password)
    },
    {
      name: 'enable',
      value: 1
    }
  ]
  db.getClient().then(client => {
    db.createSqlText({func: `query`, table: `user`, params: ['*']}).where(where).run(client).then((result) => {
      if (result.length > 0) {
        req.session.user = result[0]
        response.success(res, `登录成功`)
      } else {
        response.error(res, `账户名或密码错误`)
      }
    }, (err) => {
      response.error(res, `出现错误`)
    })
  })
})

/**
 * @api {post} /user/info 获取用户信息
 * @apiDescription 获取用户信息
 * @apiName user-info
 * @apiGroup User
 * @apiSuccess {Number} id 用户的ID
 * @apiSuccess {String} username 用户的账号
 * @apiSuccess {String} phone 手机号码
 * @apiSuccess {String} email 邮箱 
 * @apiSuccess {Number} user_type 用户类型，1为管理员
 * @apiSuccess {String} name 用户姓名
 * @apiSuccess {Number} sex 用户性别
 * @apiSuccessExample {json} Success-Response:
 *  {
 *      "code" : 200,
 *      "data" : {}
 *  }
 * @apiUse UserNotFoundError
 * @apiSampleRequest /user/info
 * @apiVersion 1.0.0
 */
router.post('/info', function(req, res, next) {
  if (!response.checkLogin(req, res)) return false
  response.returnByEntity(res, req.session.user, 'userInfoOutput')
})

/**
 * @api {post} /user/insert 插入用户
 * @apiDescription 插入用户
 * @apiName user-insert
 * @apiGroup User
 * @apiParam {string} username 用户名 *
 * @apiParam {string} password 密码(MD5加密) *
 * @apiParam {string} phone 手机号码
 * @apiParam {string} whchat_id 微信ID
 * @apiParam {string} email 邮箱
 * @apiParam {String} name 姓名
 * @apiParam {Number} sex 性别
 * @apiSuccessExample {json} Success-Response:
 *  {
 *      "code" : 200,
 *      "data" : "插入成功"
 *  }
 * @apiError {json} result 
 * @apiUse Error
 * @apiVersion 1.0.0
 * @apiSampleRequest /user/insert
 */
router.post('/insert', function(req, res, next) {
  let check = request.checkParams(req.body, 'userInsertInput')
  if (check.error) {
    response.errorList(res, check.data)
    return false
  }
  let data = check.data
  data.password = Base64.encode(md5(data.password))
  db.getClient().then(client => {
    db.createSqlText({func: 'insert', table: 'user', params: data}).run(client).then((result) => {
      response.success(res, '插入成功')
    }, () => {
      response.error(res, '插入失败')
    })
  })
})

/**
 * @api {post} /user/update 更新用户
 * @apiDescription 更新用户
 * @apiName user-update
 * @apiGroup User
 * @apiParam {Number} id 用户ID *
 * @apiParam {string} username 用户名 *
 * @apiParam {Number} user_type 用户类型 1是管理员
 * @apiParam {string} phone 手机号码
 * @apiParam {string} whchat_id 微信ID
 * @apiParam {string} email 邮箱
 * @apiParam {String} name 姓名
 * @apiParam {Number} sex 性别
 * @apiSuccessExample {json} Success-Response:
 *  {
 *      "code" : 200,
 *      "data" : "更新用户成功"
 *  }
 * @apiUse Error
 * @apiSampleRequest /user/update
 * @apiVersion 1.0.0
 */
router.post('/update', function(req, res, next) {
  // 目前是管理员进行处理, 判断是不是管理员
  if (!response.checkLogin(req, res)) return false
  if (req.session.user.user_type !== 1) {
    response.error(res, `请使用管理员登录`)
    return false
  }
  // 处理数据
  let check = request.checkParams(req.body, 'userUpdateInput')
  if (check.error) {
    response.errorList(res, check.data)
    return false
  }
  let data = {...check.data}
  db.getClient().then(client => {
    db.createSqlText({func: 'update', table: 'user', params: data}).where([{name: 'id', value: data.id}]).run(client).then((result) => {
      response.success(res, '更新成功')
    }, () => {
      response.error(res, '更新失败')
    })
  })
});
/**
 * @api {post} /user/reset_password 重置密码（管理员操作）
 * @apiDescription 重置密码（管理员操作）
 * @apiName user-reset_password
 * @apiGroup User
 * @apiParam {Number} id 用户ID *
 * @apiSuccessExample {json} Success-Response:
 *  {
 *      "code" : 200,
 *      "data" : "重置成功，密码为xxxxxx"
 *  }
 * @apiUse Error
 * @apiSampleRequest /user/reset_password
 * @apiVersion 1.0.0
 */

router.post('/reset_password', function(req, res, next) {
  // 目前是管理员进行处理, 判断是不是管理员
  if (!response.checkLogin(req, res)) return false
  if (req.session.user.user_type !== 1) {
    response.error(res, `请使用管理员登录`)
    return false
  }
  // 处理数据
  let check = request.checkParams(req.body, 'byIdInput')
  if (check.error) {
    response.errorList(res, check.data)
    return false
  }
  // 生成密码，对密码加密
  let id = check.data.id
  let newPassword = unit.getRandStr(6)
  let data = {password: Base64.encode(md5(newPassword))}
  // 数据库操作
  db.getClient(client => {
    db.createSqlText({func: 'update', table: 'user', params: data}).where([{name: 'id', value: data.id}]).run(client).then((result) => {
      response.success(res, `重置成功，密码为${newPassword}`)
    }, () => {
      response.error(res, '重置密码失败')
    })
  })
})

/**
 * @api {post} /user/remove 删除用户（管理员操作）
 * @apiDescription 删除用户（管理员操作）
 * @apiName user-remove
 * @apiGroup User
 * @apiParam {Number[]} id 用户ID *
 * @apiSuccessExample {json} Success-Response:
 *  {
 *      "code" : 200,
 *      "data" : "删除成功"
 *  }
 * @apiUse Error
 * @apiSampleRequest /user/remove
 * @apiVersion 1.0.0
 */
router.post('/remove', function (req, res, next) {
  // 目前是管理员进行处理, 判断是不是管理员
  if (!response.checkLogin(req, res)) return false
  if (req.session.user.user_type !== 1) {
    response.error(res, `请使用管理员登录`)
    return false
  }
  // 处理数据
  req.body.id = [21]
  let check = request.checkParams(req.body, 'byIdInput', true)
  if (check.error) {
    response.errorList(res, check.data)
    return false
  }
  let data = check.data.id
  db.getClient().then(client => {
    db.createSqlText({func: 'update', table: 'user', params: {enable: 0}}).where([{name: 'id', value: data, type: 'in'}]).run(client).then((result) => {
      response.success(res, `删除成功`)
    }, () => {
      response.error(res, '删除失败')
    })
  })
})
/**
 * @api {post} /user/download 下载操作
 * @apiDescription 下载操作
 * @apiName user-download
 * @apiGroup User
 * @apiUse Error
 * @apiSampleRequest /user/remove
 * @apiVersion 1.0.0
 */
router.post('/download', function(req, res, next) {
  let data = [[1, 2, 3], [true, false, null, 'sheetjs'], ['foo', 'bar', new Date('2014-02-19T14:30Z'), '0.3'], ['baz', null, 'qux']];
  let range = {s: {c: 0, r:0 }, e: {c:0, r:3}}; // A1:A4
  let option = {'!merges': [ range ]};

  let buffer = xlsx.build([{name: "mySheetName", data: data}], option);
  
  let filename = '测试编码.xlsx';
  filename = urlencode(filename);

  res.set({
    'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'Content-Disposition': `filename=${filename}`,
    'Content-Length': buffer.length
  });
  res.send(buffer,'binary');
  //不用转stream
  //let bufferStream = new stream.PassThrough();
  //bufferStream.end(buffer);
  //  bufferStream.pipe(res);
})
module.exports = router;

